/* Copyright (c) [2025] [zhi1208@126.com]
 * SPDX-License-Identifier: MIT
 */

/*********************
 *      INCLUDES
 *********************/
#include "bsp_sw_i2c.h"

/*********************
 *      DEFINES
 *********************/

/**********************
 *      TYPEDEFS
 **********************/

/**********************
 *  STATIC PROTOTYPES
 **********************/

/**********************
 *  STATIC VARIABLES
 **********************/

/**********************
 *      MACROS
 **********************/

/**********************
 *   GLOBAL FUNCTIONS
 **********************/
void sw_i2c_start(sw_i2c_t *sw_i2c)
{
    sw_i2c->set_sda(1);
    sw_i2c->set_scl(1);

    sw_i2c->set_sda(0);
    sw_i2c->set_scl(0);
}

void sw_i2c_stop(sw_i2c_t *sw_i2c)
{
    sw_i2c->set_sda(0);
    sw_i2c->set_scl(1);
    sw_i2c->set_sda(1);
}

void sw_i2c_send_ack(sw_i2c_t *sw_i2c, uint8_t ack)
{
    sw_i2c->set_sda(ack);
    sw_i2c->set_scl(1);
    sw_i2c->set_scl(0);
}

uint8_t sw_i2c_recv_ack(sw_i2c_t *sw_i2c)
{
    uint8_t ack = 0;
    sw_i2c->set_sda(1);
    sw_i2c->set_scl(1);
    ack = sw_i2c->read_sda();
    sw_i2c->set_scl(0);
    return ack;
}

void sw_i2c_send_byte(sw_i2c_t *sw_i2c, uint8_t byte)
{
    for (int8_t i = 7; i >= 0; --i)
    {
        sw_i2c->set_sda((byte >> i) & 0x01);
        sw_i2c->set_scl(1);
        sw_i2c->set_scl(0);
    }
}

uint8_t sw_i2c_recv_byte(sw_i2c_t *sw_i2c)
{
    uint8_t byte = 0;
    sw_i2c->set_sda(1);

    for (uint8_t i = 0; i < 8; ++i)
    {
        byte <<= 1;
        sw_i2c->set_scl(1);
        byte |= sw_i2c->read_sda();
        sw_i2c->set_scl(0);
    }

    return byte;
}

/**********************
 *   STATIC FUNCTIONS
 **********************/